package com.tsinkai.ettp.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ExcelRead {

	
	@SuppressWarnings("resource")
	public static void main(String[] args) {
		//excel所在地址
		String path = "E:\\demo\\excel\\one.xlsx";
		
		File file = new File(path);
		InputStream in = null;
		
		try {
			in = new FileInputStream(file);
			//文件后缀名
			String type = path.substring(path.indexOf(".")+1);
			Workbook wb;
			
			//根据后缀名选择不同版本的实现2003/2007版，分别对应xls/xlsx
			if("xlsx".equals(type) || "XlSX".equals(type)) {
				wb = new XSSFWorkbook(in);
			}else if("xls".equals(type) || "XLS".equals(type)) {
				wb = new HSSFWorkbook(in);
			}else {
				System.out.println("文件后缀格式有误");
				return;
			}
			//获取sheet
			Sheet sheet = wb.getSheetAt(0);
			//总行数
			int rsRows = sheet.getPhysicalNumberOfRows();
			//总列数
			int rsColumn = sheet.getRow(0).getPhysicalNumberOfCells();
			
			//存放excel的二维数组
			String[][] data = new String[rsRows][rsColumn];
//			Row row ;
			Cell cell;
			for(int i =0;i<rsRows;i++) {
				for(int j =0;j<rsColumn;j++) {
					cell = sheet.getRow(i).getCell(j);
					//把非string类型的单元格设置成string
					cell.setCellType(CellType.STRING);
					data[i][j] = cell.getStringCellValue();
				}
			}
			
			//打印结果
			for(int i=0;i<data.length;i++) {
				for(int j=0;j<data[i].length;j++) {
					System.out.print(data[i][j]+"\t");
				}
				System.out.println();
			}
			
		} catch (FileNotFoundException e) {
			System.out.println("读取文件失败");
			e.printStackTrace();
		} catch (IOException e) {
			System.out.println("创建workbook失败");
			e.printStackTrace();
		}finally {
			try {
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		
		
	
	}

}
